package cn.org.xwb.bookmall.model.service.impl;

import cn.org.xwb.bookmall.model.mapper.LiuImgMapper;
import cn.org.xwb.bookmall.model.po.Authority;
import cn.org.xwb.bookmall.model.po.CommentsImg;
import cn.org.xwb.bookmall.model.po.Liu;
import cn.org.xwb.bookmall.model.mapper.LiuMapper;
import cn.org.xwb.bookmall.model.po.LiuImg;
import cn.org.xwb.bookmall.model.service.ILiuService;
import cn.org.xwb.bookmall.model.utils.BookRedisUtil;
import cn.org.xwb.bookmall.model.vo.CommentsVo;
import cn.org.xwb.bookmall.model.vo.LiuVo;
import cn.org.xwb.common.page.dto.PageResult;
import cn.org.xwb.common.page.utils.PageUtil;
import cn.org.xwb.common.redis.utils.RedisUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xwb
 * @since 2023-12-18
 */
@Service
public class LiuServiceImpl extends ServiceImpl<LiuMapper, Liu> implements ILiuService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private BookRedisUtil bookRedisUtil;

    private String getKeyLiu() {
        return bookRedisUtil.getRedisKeyUser("liu", "");
    }

    public List<LiuVo> findAndCacheAll() {
        // 查询所有
        List<LiuVo> liuVos = baseMapper.selectAll();
        // 缓存
        Boolean res = redisUtil.setList(getKeyLiu(), liuVos);
        // 失败
        if (!res) return null;
        return liuVos;
    }

    public List<LiuVo> findAllFromCache() {
        // 查询缓存
        List<LiuVo> liuVos = (ArrayList<LiuVo>) redisUtil.get(getKeyLiu());
        // 缓存中不存在，则从数据库中查询，并缓存
        if (Objects.isNull(liuVos)) liuVos = findAndCacheAll();
        // 发生异常
        if (Objects.isNull(liuVos)) return null;
        // 成功
        return liuVos;
    }

    @Autowired
    private LiuImgMapper liuImgMapper;

    @Transactional
    public Boolean delLiu(Long id) {
        LambdaQueryWrapper<LiuImg> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LiuImg::getLiuId, id);
        int res = liuImgMapper.delete(wrapper);
        // if (res < 1) {
        //     System.out.println(res);
        //     TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        //     return false;
        // }
        res += baseMapper.deleteById(id);
        if (res < 1) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        List<LiuVo> liuVos = findAndCacheAll();
        if (Objects.isNull(liuVos)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
        return true;
    }

    public List<LiuVo> getLiu(Long userId, String kw) {
        List<LiuVo> liuVos = findAllFromCache();
        if (Objects.nonNull(liuVos)) Collections.reverse(liuVos);
        if (Objects.nonNull(liuVos) && Objects.nonNull(userId)) {
            liuVos = liuVos.stream().filter(liuVo -> liuVo.getUserId() == userId).toList();
        }
        if (Objects.nonNull(liuVos) && Objects.nonNull(kw)) {
            liuVos = liuVos.stream().filter(liuVo -> liuVo.getContent().contains(kw)).toList();
        }
        return liuVos;
    }

    public PageResult<List<LiuVo>> getLiuPage(Integer current, Integer pageSize, Long userId, String kw) {
        // 从缓存中获取所有的用户留言
        List<LiuVo> liuVos = findAllFromCache();
        // 没有用户留言直接返回
        if (Objects.isNull(liuVos)) return null;
        // 根据用户留言发表时间进行逆序
        Collections.reverse(liuVos);
        // 根据用户编号进行筛选
        if (Objects.nonNull(userId)) {
            liuVos = liuVos.stream().filter(liuVo -> liuVo.getUserId() == userId).toList();
        }
        // 根据搜索关键词进行筛选
        if (Objects.nonNull(kw)) {
            liuVos = liuVos.stream().filter(
                    liuVo -> liuVo.getContent().contains(kw) || liuVo.getUsername().contains(kw)
            ).toList();
        }
        // 对用户留言进行分页
        // 计算分页后的页数
        Integer pageCnt = PageUtil.getPageCnt(liuVos.size(), pageSize);
        // 分页数据
        liuVos = (List<LiuVo>) PageUtil.getPageData(liuVos, current, pageSize);
        return new PageResult<>(current, pageSize, liuVos.size(), pageCnt, liuVos);
    }

}
